package com.base.cn.platform.os.service.qa.qaattend;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.dao.qa.qaattend.QaAttendDao;
import com.base.cn.platform.os.entity.qa.qaattend.QaAttend;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.entity.qa.question.QuestionCondition;
import com.base.cn.platform.os.entity.qa.record.QaGainAttendRecord;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.manage.user.user.SetUserDataService;
import com.base.cn.platform.os.service.qa.question.QaQuestionBiz;
import com.base.cn.platform.os.service.qa.record.QaGainAttendRecordBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 问答旁听Biz
 * @author LIZHIPENG
 * @since 2018/4/26
 */
@Service
public class QaAttendBiz extends BaseBiz<QaAttend, QaAttendDao> {

    @Autowired
    private SetUserDataService<QaAttend> setUserDataService;

    @Autowired
    private QaGainAttendRecordBiz qaGainAttendRecordBiz;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private QaQuestionBiz qaQuestionBiz;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;

    public BigDecimal attendCount(QaAttend attend){
        String whereSql = getWhereSql(attend);
        return this.count(whereSql);
    }

    /**
     * 添加追问记录
     * @param qaAttendList
     */
    @Transactional(rollbackFor = IllegalArgumentException.class )
    public void addAttend(List<QaAttend> qaAttendList){
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.ATTENT);
        List<QaGainAttendRecord> gainAttendRecordList = new ArrayList<>();
        //同时修改围观人数
        String qaIds = qaAttendList.stream().map(e->e.getQuestionId().toString()).distinct().collect(Collectors.joining(","));
        if(StringUtils.isNotEmpty(qaIds)){
            QuestionCondition condition =new QuestionCondition();
            condition.setIds(qaIds);
            List<QaQuestion> questionByIds = qaQuestionBiz.findQuestionByIds(condition);
            questionByIds.forEach(v->{
                QaQuestion qaQuestion = new QaQuestion();
                qaQuestion.setId(v.getId());
                qaQuestion.setAttendNum( v.getAttendNum()+1);
                qaQuestionBiz.addOrUpdateQuestion(qaQuestion);
            });
        }

        qaAttendList.forEach(e->{
            QaGainAttendRecord record = new QaGainAttendRecord();
            record.setQuestionId(e.getQuestionId());
            record.setOrderId(e.getOrderId());
            record.setOrderNo(e.getOrderNo());
            record.setDetailsId(e.getDetailsId());
            record.setPayType(e.getPayType());
            record.setUserId(e.getUserId());
            record.setUserType(1);//1.系统
            record.setReceiptorId(new BigDecimal(0));
            double sysTerrace = Double.parseDouble(configMap.get("sysTerrace"))*10D /100D;//平台分成比例
            double amount = e.getPrice().doubleValue()*sysTerrace;
            record.setAmount(amount);
            record.setStatus(2);
            gainAttendRecordList.add(record);

            //2.专家
            QaGainAttendRecord record2 = record.clone();
            record2.setStatus(1);
            record2.setUserType(2);//2.专家
            record2.setReceiptorId(e.getTeacherId());//获取专业ID
            e.setTeacherId(null);
            double user = Double.parseDouble(configMap.get("user"))*10D /100D;//用户分成比例
            amount = e.getPrice().doubleValue()*user;
            record.setAmount(amount);
            gainAttendRecordList.add(record2);

            //2.旁听对应答问的提问人
            QaGainAttendRecord record3 = record.clone();
            record3.setStatus(1);
            record3.setUserType(3);//3.用户ID
            //问答提问者的ID
            record3.setReceiptorId(e.getQaQuestion().getUserId());
            double teacher = Double.parseDouble(configMap.get("teacher"))*10D /100D;//讲师分成比例
            amount = e.getPrice().doubleValue()*teacher;
            record.setAmount(amount);
            gainAttendRecordList.add(record3);

        });
        //保存旁听支付分成记录
        qaGainAttendRecordBiz.addGainAttendRecord(gainAttendRecordList);
        //保存旁听支付记录
        this.batchSave(qaAttendList);
        //添加积分
        List<BigDecimal> userIdList = qaAttendList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
        cusUserIntegralService.batchAddUserIntegral(userIdList, ActionKey.ONLOOK);
    }

    /**
     * 分页查询旁听列表
     * @param qaAttend 查询条件
     * @param page 分页
     * @param createUserData 是否查询用户数据： true：是，false：否
     * @return
     */
    public PageInfo<QaAttend> findQaAttendListPage(QaAttend qaAttend, Pagination page, boolean createUserData){
        String whereSql = getWhereSql(qaAttend);
        PageInfo<QaAttend> qaAttendPageInfo = this.findPage(whereSql, page, null);
        qaAttendPageInfo.setList(this.setCreateUserData(qaAttendPageInfo.getList(), createUserData));
        return qaAttendPageInfo;
    }

    /**
     * 条件查询问题围观列表
     * @param qaAttend 查询条件
     * @param crateUserData 围观用户
     * @return
     */
    public List<QaAttend> findQaAttendList(QaAttend qaAttend, boolean crateUserData){
        String whereSql = getWhereSql(qaAttend);
        List<QaAttend> attendList = this.find(whereSql, qaAttend.getCount(), null);
        return this.setCreateUserData(attendList, crateUserData);
    }

    //================================================

    /**
     * 拼接sql语句
     * @param qaAttend 拼接条件
     * @return
     */
    private String getWhereSql(QaAttend qaAttend){
        String whereSql = "status != 3";
        if(ObjectUtils.isNotEmpty(qaAttend)){
            if(DataUtil.idIsNotNull(qaAttend.getId())){
                whereSql += " and id="+ qaAttend.getId();
            }
            if(DataUtil.idIsNotNull(qaAttend.getQuestionId())){
                whereSql += " and questionId=" + qaAttend.getQuestionId();
            }
            if(StringUtils.isNotEmpty(qaAttend.getQuestionIds())){
                whereSql += " and questionId in ("+ qaAttend.getQuestionIds() +")";
            }
            if(DataUtil.idIsNotNull(qaAttend.getUserId())){
                whereSql += " and userId="+ qaAttend.getUserId();
            }
            if(ObjectUtils.isNotEmpty(qaAttend.getStatus())){
                whereSql += " and status="+ qaAttend.getStatus();
            }
        }
        return whereSql;
    }

    /**
     * 旁听列表设置用户数据
     * @param attendList 旁听列表
     * @param createUserData 是否设置旁听用户信息（true：是，false：否）
     * @return
     */
    private List<QaAttend> setCreateUserData(List<QaAttend> attendList, boolean createUserData){
        if(ObjectUtils.isNotEmpty(attendList) && createUserData){
            setUserDataService.setUserData(attendList, createUserData);
        }
        return attendList;
    }
}
